const dbconfig = require("../util/dbconfig");
const { use } = require("../routes");
// 阿里云短信的配置引入
const Core = require("@alicloud/pop-core");
const aliconfig = require("../util/aliconfig");
let client = new Core(aliconfig.alicloud);
var requestOption = {
    method: "POST",
};

function rand(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}
let validate = [];
// 表示已经发送过验证码了
let testphone = (newphone) => {
    for (let item of validate) {
        if (item.phone == newphone) {
            return true;
        }
    }
    return false;
};
let patchPhone = (phone, code) => {
    for (let item of validate) {
        if (item.phone == phone && item.code == code) {
            return "login";
        }
    }
    return "error";
};
// 每过60s删除一项发送过验证码的手机号,就那个60秒只能发送一次的node实现形式
// setInterval(()=>{
//     if(validate != []){

//         console.log('shift = ',validate.shift());
//     }
// },60000)

// 检测手机验证码登录是否为第一次登录
let phoneLoginBind = async (phone) => {
    let sql = "select * from user where username=? or phone=?";
    let sqlArr = [phone, phone];
    let res = await dbconfig.asyncSqlconnect(sql, sqlArr);
    // console.log('res',res)
    if (res.length) {
        res[0].userinfo = await getuserinfo(res[0].phone);
        return res;
    } else {
        // 用户第一次登录，进行注册，并传入数据到数据库
        let res = await regUser(phone);
        // 获取用户副表的详情
        if (res) {
            res[0].userinfo = await getuserinfo(res[0].phone);
        } else {
            console.log("error of res");
        }
        return res;
    }
};

// 用户注册的方法
let regUser = async function (phone) {
    // 用户默认头像
    let userpic =
        "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1741476901,4013212021&fm=11&gp=0.jpg";
    let sql = `insert into user(username,userpic,password,phone) value (?,?,?,?)`;
    let sqlArr = [phone, userpic, phone, phone];
    let res = await dbconfig.asyncSqlconnect(sql, sqlArr);
    // 这里是Rows，注意一点细节
    if (res.affectedRows == 1) {
        // 执行成功，然后获取用户信息,可以封装成一个方法
        let user = await getUser(phone);
        // 然后还需要根据用户信息创建一个用户的副表，存储用户私人信息
        let userinfo = await createuserinfo(user[0].phone);
        if (userinfo.affectedRows == 1) {
            return user;
        } else {
            return false;
        }
    } else {
        return false;
    }
};

// 获取用户信息，这里先使用phone作为参数
let getUser = async (phone) => {
    let sql = "select * from user where phone=?";
    let sqlArr = [phone];
    return dbconfig.asyncSqlconnect(sql, sqlArr);
};
// 创建用户副表
let createuserinfo = async (user_id) => {
    let sql = `insert into userinfo(user_id,age,sex,job) value (?,?,?,?)`;
    let sqlArr = [user_id, 20, 1, "学生"];
    return dbconfig.asyncSqlconnect(sql, sqlArr);
};
// 获取用户副表中的详情
let getuserinfo = async (user_id) => {
    let sql = "select * from userinfo where user_id=?";
    let sqlArr = [user_id];
    return dbconfig.asyncSqlconnect(sql, sqlArr);
};
//调用阿里云接口发送短信验证码
sendCoreCode = (req, res) => {
    let phone = req.query.phone;
    let randomcode = rand(1000, 9999);
    // 这就是要发送的配置，里面的number是接收验证码的号码，TemplateParam为发送的验证码，其他的为自身的配置
    var params = {
        RegionId: "cn-hangzhou",
        PhoneNumbers: phone,
        SignName: "chengsong商城",
        TemplateCode: "SMS_205391612",
        TemplateParam: JSON.stringify({ code: randomcode }),
    };
    client.request("SendSms", params, requestOption).then(
        (result) => {
            console.log(JSON.stringify(result));
            if (result) {
                res.send({
                    code: 200,
                    yourcode: randomcode,
                    msg: "发送成功",
                });
                validate.push({
                    phone: phone,
                    code: randomcode,
                });
            } else {
                res.send({
                    code: 400,
                    msg: "发送失败",
                });
            }
        },
        (ex) => {
            console.log(ex);
        }
    );
};
//模拟验证码发送接口
sendcode = (req, res) => {
    // 没有req.body，因为是get请求；只有post请求才有body
    let phone = req.query.phone;
    let randomcode = rand(1000, 9999);
    if (!testphone(phone)) {
        validate.push({
            phone: phone,
            code: randomcode
        });
        res.send({
            code: 200,
            body: req.body,
            randomcode: randomcode,
            msg: "发送成功",
        });
    } else {
        res.send({
            code: "500",
            msg: "请不要重复发送",
        });
    }
};

// 验证码登录
codeLogin = async (req, res) => {
    let { phone, code } = req.query;
    if (testphone(phone)) {
        // 检测是否对这个手机号发送过验证码与验证码是否正确
        let state = patchPhone(phone, code);
        if (state == "login") {
            let user = await phoneLoginBind(phone);
            res.send({
                code: 200,
                user: user,
                msg: "登录成功",
            });
        } else {
            res.send({
                code: 404,
                msg: "登录失败",
            });
        }
    } else {
        res.send({
            code: 400,
            msg: "未发送验证码",
        });
    }
};
module.exports = {
    sendcode,
    codeLogin,
    sendCoreCode,
    validate,
};
